/*
**NCS Network Library Routines and Procedures
**This module provide the network API with socket for NCS 
**Because of using only UDP socket,and providing UDP API
**
**Copyright (C) 2015-xxxx andisat <www.andisat.com>
**
**Author: andisat
**Date:2015-12
**
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include "event.h"
#include "ncs_log.h"
#include "ncs_network.h"
#include "ncs_cfg.h"
#include "ncs_dev.h"
#include "ncs_msg.h"
#include "ncs_serv.h"
#include "ncs_db.h"

struct ncs_object g_ncs_base;

char *progam="ncs_servd";
char *version="1.0.0";

static void usage (int status)
{
    if (status != 0)
        fprintf(stderr, "Try %s -h for more information.\n", progam);
    else
    {    
          printf ("Usage : %s [OPTION...]\n\n\
        -r, --retransmit_max        Max retransmits of sending packets\n\
        -t, --retransmit_timeout   Timeout of retransmiting packets\n\
        -p, --default_udp_port      Default udp port\n\
        -l, --set_log_output      Log output: 1:stdout,2:syslog,3:file\n\
        -?, --help               Display this help and exit\n\
        \n", progam);
    }

    exit (status);
}

int main(int argc,char **argv)
{
    int option;
    int retransmit_max=DEF_RETRANSMIT_MAX;
    int retransmit_timeout=DEF_RETRANSMIT_TIMEOUT;
    short port=DEF_UDP_PORT;
    
    while((option=getopt(argc,argv,"r:t:p:l:h")) != -1)
    {
        switch(option)
        {
            case 'r': 
                retransmit_max = atoi(optarg);
                break;
            case 't':
                retransmit_timeout = atoi(optarg);
                break;
            case 'p':
                port=atoi(optarg);
                break;
            case 'l':
                log_flag=atoi(optarg);
                break;
            case 'h':
                usage(0);
                break;
            default:
                usage(1);
                break;
        }
    }
    
    if(ncs_openlog(progam, LOG_PID | LOG_CONS,LOG_DAEMON))
        event_set_log_callback(ncs_log_new);

    ncs_log(INFO,"Starting %s %s ... ...",progam,version);

    init_ncs(&g_ncs_base);
    
    g_ncs_base.g_retransmit_max = retransmit_max;
    g_ncs_base.g_retransmit_timeout = retransmit_timeout;
    g_ncs_base.servd_port = port;
    
    if(0 != db_open())
    {
        ncs_log(ERR,"%s open ncs database error",__func__);
        return 1;
    }  
    
    ncs_creat_client_un(&g_ncs_base);
    ncs_get_cfginfo_from_db(&g_ncs_base);    
    ncs_get_dev_from_db(&g_ncs_base);
    ncs_send_rdcfg_finish_msg(g_ncs_base.client_fd);
    
    event_base_dispatch(g_ncs_base.g_base);
    event_base_free(g_ncs_base.g_base);
    free_ncs(&g_ncs_base);
    db_close();
    
    return 0;
}

